System.Collections.Generic.List<T>
is a generic collection that is designed for performance and not inheritance. For example, it
does not contain virtual members that make it easier to change the behavior of an inherited class. That means that future attempts to expand the
behavior will be spoiled because the extension points simply aren’t there. Instead, one of the following generic collections should be used:
-
System.Collections.Generic.IEnumerable<T>
-
System.Collections.Generic.IReadOnlyCollection<T>
-
System.Collections.Generic.ICollection<TKey>
-
System.Collections.Generic.IReadOnlyList<T>
-
System.Collections.Generic.IList<TKey>
-
System.Collections.ObjectModel.Collection<T>
-
System.Collections.ObjectModel.ReadOnlyCollection<T>
-
System.Collections.ObjectModel.KeyedCollection<TKey, Titem>
This rule raises an issue every time a System.Collections.Generic.List<T>
is exposed:
- As an externally visible member.
- As the return type of an externally visible method.
- As a parameter type of an an externally visible method.
Noncompliant code example
namespace Foo
{
public class Bar
{
public List<T> Method1(T arg) // Noncompliant
{
//...
}
}
}
Compliant solution
namespace Foo
{
public class Bar
{
public Collection<T> Method1(T arg)
{
//...
}
}
}